package com.duowei.diandan.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.preference.Preference;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.duowei.diandan.BuildConfig;
import com.duowei.diandan.R;
import com.duowei.diandan.app.App;
import com.duowei.diandan.app.InitManager;
import com.duowei.diandan.constant.NetConfig;
import com.duowei.diandan.constant.OrderMode;
import com.duowei.diandan.constant.Settings;
import com.duowei.diandan.db.entry.Yhjbqk;
import com.duowei.diandan.fragment.dialog.PromptDialogFragment;
import com.duowei.diandan.util.NetUtils;
import com.duowei.diandan.util.Post6Listener;
import com.duowei.diandan.util.UpdateHelper;
import com.jaredrummler.android.colorpicker.ColorPreference;
import com.takisoft.fix.support.v7.preference.PreferenceFragmentCompat;

import java.util.List;

public class SettingsActivity extends BaseActivity {
    private static final String TAG = "SettingsActivity";

    private boolean mNeedManageOverlayPermission = false;
    private boolean mNeedFinish = false;

    public static void openSettingsActivity(Context context) {
        Intent intent = new Intent(context, SettingsActivity.class);
        intent.putExtra("open", true);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate: start");

        checkManageOverlayPermission();

        setTitle(R.string.title_activity_settings);

        boolean openSetting = getIntent().getBooleanExtra("open", false);

        if (!openSetting && Settings.checkSettings(false)) {
            mNeedFinish = true;
            if (!mNeedManageOverlayPermission) {
                Log.d(TAG, "onCreate: finish");
                startActivity();
                finish();
                return;
            }
        }

        setContentView(R.layout.activity_settings);
        ListView headerList = findViewById(R.id.list);

        String[] headers = new String[]{"基本", "点餐模式", "功能选择", "界面设置", "打印", "使用说明", "关于"};
        headerList.setAdapter(new HeaderAdapter(this, headers));
        headerList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        headerList.setOnItemClickListener((parent, view, position, id) -> {
            String title = headers[position];
            setPreferenceFragment(title);
        });

        headerList.setItemChecked(0, true);
        setPreferenceFragment("基本");

        InitManager.getInstance().setCanDownTime(false);

        Log.d(TAG, "onCreate: end");
    }

    private void checkManageOverlayPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!android.provider.Settings.canDrawOverlays(App.getApp())) {
                mNeedManageOverlayPermission = true;
                Toast.makeText(this, "运行自助点餐,需要悬浮窗权限", Toast.LENGTH_SHORT).show();

                Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, 1);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (android.provider.Settings.canDrawOverlays(App.getApp())) {
                    Toast.makeText(this, "获取权限成功", Toast.LENGTH_SHORT).show();

                    if (mNeedFinish) {
                        startActivity();
                        finish();
                    }
                } else {
                    Toast.makeText(this, "获取权限失败,自动点餐不能启动", Toast.LENGTH_SHORT).show();
                    finish();
                }
            }
        }
    }

    private void setPreferenceFragment(String title) {
        Fragment fragment = getSupportFragmentManager().findFragmentByTag(title);
        if (fragment == null) {
            if ("使用说明".equals(title)) {
                WebFragment webFragment = new WebFragment();
                getSupportFragmentManager().beginTransaction()
                        .replace(R.id.prefs, webFragment, title)
                        .commit();
            } else {
                ItemFragment itemFragment = ItemFragment.newInstance(title);
                getSupportFragmentManager().beginTransaction()
                        .replace(R.id.prefs, itemFragment, title)
                        .commit();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_settings, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_save) {
            Settings.updateSettings();
            if (Settings.checkSettings(true)) {

                if (Settings.RESTART_DOWNLOAD) {
                    Settings.RESTART_DOWNLOAD = false;

                    Intent intent = new Intent(SettingsActivity.this, DownloadActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                    finish();

                } else {
                    PromptDialogFragment fragment = PromptDialogFragment.newInstanceSettingsSave();
                    fragment.setOnBtnClickListener(new PromptDialogFragment.OnBtnClickListener() {
                        @Override
                        public void onCancelBtnClick() {
                            Intent intent = new Intent(SettingsActivity.this, WelcomeActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(intent);
                            finish();
                        }

                        @Override
                        public void onOkBtnClick() {
                            Intent intent = new Intent(SettingsActivity.this, DownloadActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(intent);
                            finish();
                        }
                    });
                    fragment.show(getSupportFragmentManager(), null);
                }
            }

            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        Toast.makeText(this, "关闭当前界面,请点击保存按钮!", Toast.LENGTH_SHORT).show();
    }

    private void startActivity() {
        Intent intent = new Intent(this, DownloadActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    private static class HeaderAdapter extends ArrayAdapter<String> {
        private static class HeaderViewHolder {
            TextView title;
        }

        private LayoutInflater mInflater;

        HeaderAdapter(@NonNull Context context, @NonNull String[] objects) {
            super(context, 0, objects);
            mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @NonNull
        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            HeaderViewHolder holder;

            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.preference_header_item, parent, false);
                holder = new HeaderViewHolder();
                holder.title = convertView.findViewById(android.R.id.title);
                convertView.setTag(holder);
            } else {
                holder = (HeaderViewHolder) convertView.getTag();
            }

            holder.title.setText(getItem(position));

            return convertView;
        }
    }

    public static class ItemFragment extends PreferenceFragmentCompat
            implements Preference.OnPreferenceClickListener {
        private static final String TAG = "ItemFragment";

        private static final String DIALOG_FRAGMENT_TAG =
                "android.support.v7.preference.PreferenceFragment.DIALOG";

        public static ItemFragment newInstance(String title) {

            Bundle args = new Bundle();
            args.putString("title", title);

            ItemFragment fragment = new ItemFragment();
            fragment.setArguments(args);
            return fragment;
        }

        // 默认用户
        private Preference mDefaultUserPreference;

        private Preference mPlateModePreference;
        private Preference mSearchBarEnablePreference;
        private Preference mColumnDeskChoicePreference;

        private SharedPreferences.OnSharedPreferenceChangeListener mOnPreferenceChangeListener =
                (sharedPreferences, s) -> {
                    Log.d(TAG, "Settings changed");

                    if (getString(R.string.pref_key_server_ip).equals(s)) {
                        Settings.setDefaultUser(null);
                    }

                    updateUi();

                    // 重新下载数据
                    if (getString(R.string.pref_key_order_mode).equals(s)
                            || getString(R.string.pref_key_countdown_enabled).equals(s)
                            || getString(R.string.pref_key_meal_position).equals(s)) {
                        Settings.RESTART_DOWNLOAD = true;
                    }
                };

        @Override
        public void onCreatePreferencesFix(@Nullable Bundle savedInstanceState, String rootKey) {
            getPreferenceManager().getSharedPreferences()
                    .registerOnSharedPreferenceChangeListener(mOnPreferenceChangeListener);

            String title = null;
            Bundle args = getArguments();
            if (args != null) {
                title = args.getString("title");
            }

            if ("基本".equals(title)) {
                addPreferencesFromResource(R.xml.pref_basic);

                // 默认用户
                mDefaultUserPreference = findPreference(getString(R.string.pref_key_default_user));
                mDefaultUserPreference.setOnPreferenceClickListener(this);

                // 返回到桌面
                findPreference(getString(R.string.pref_key_return_desk))
                        .setOnPreferenceClickListener(preference -> {
                            Intent startMain = new Intent(Intent.ACTION_MAIN);
                            startMain.addCategory(Intent.CATEGORY_HOME);
                            startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(startMain);
                            return true;
                        });

            } else if ("点餐模式".equals(title)) {
                addPreferencesFromResource(R.xml.pref_mode);

                mPlateModePreference = findPreference(getString(R.string.pref_key_plate_mode));
                mSearchBarEnablePreference = findPreference(getString(R.string.pref_key_search_bar_enable));
                mColumnDeskChoicePreference = findPreference(getString(R.string.pref_key_column_desk_choice));

            } else if ("功能选择".equals(title)) {
                addPreferencesFromResource(R.xml.pref_function);

            } else if ("界面设置".equals(title)) {
                addPreferencesFromResource(R.xml.pref_interface);

            } else if ("打印".equals(title)) {
                addPreferencesFromResource(R.xml.pref_print);

            } else if ("关于".equals(title)) {
                addPreferencesFromResource(R.xml.pref_about);

                // 版本号
                findPreference("pref_version_name").setSummary(BuildConfig.VERSION_NAME);

                findPreference("pref_check_update")
                        .setOnPreferenceClickListener(preference -> {
                            new UpdateHelper((BaseActivity) getActivity()).checkUpdate();
                            return true;
                        });
            }

            //
            updateUi();
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            getPreferenceManager().getSharedPreferences()
                    .unregisterOnSharedPreferenceChangeListener(mOnPreferenceChangeListener);
        }

        @Override
        public void onDisplayPreferenceDialog(Preference preference) {
            // check if dialog is already showing
            if (getFragmentManager().findFragmentByTag(DIALOG_FRAGMENT_TAG) != null) {
                return;
            }

            if (preference instanceof ColorPreference) {
                final DialogFragment f = ((ColorPreference) preference).createDialog();
                f.setTargetFragment(this, 0);
                f.show(getFragmentManager(), DIALOG_FRAGMENT_TAG);
            } else {
                super.onDisplayPreferenceDialog(preference);
            }
        }

        private void updateUi() {
            Settings.updateSettings();

            // 默认用户
            if (mDefaultUserPreference != null) {

                if (Settings.DEFAULT_YHJBQK != null) {
                    mDefaultUserPreference.setSummary(Settings.DEFAULT_YHJBQK.getYhmc());
                } else {
                    mDefaultUserPreference.setSummary(null);
                }
            }

            // 点餐模式分类
            if (mPlateModePreference != null && mSearchBarEnablePreference != null
                    && mColumnDeskChoicePreference != null) {
                if (Settings.ORDER_MODE == OrderMode.SELF_SERVICE
                        || Settings.ORDER_MODE == OrderMode.SELF_SERVICE_MEMBER) {
                    mPlateModePreference.setVisible(true);
                    mSearchBarEnablePreference.setVisible(false);
                    mColumnDeskChoicePreference.setVisible(false);

                } else if (Settings.ORDER_MODE == OrderMode.COMMIT) {
                    mPlateModePreference.setVisible(false);
                    mSearchBarEnablePreference.setVisible(true);
                    mColumnDeskChoicePreference.setVisible(true);
                }
            }
        }

        @Override
        public boolean onPreferenceClick(final Preference preference) {
            String key = preference.getKey();

            if (key.equals(getString(R.string.pref_key_default_user))) {
                // 点击 默认用户
                getUserFromServer();

                return true;
            }

            return false;
        }

        private void getUserFromServer() {
            NetUtils.post6(NetConfig.getServerUrl(), Yhjbqk.querySql(), Yhjbqk.class, new Post6Listener<Yhjbqk>() {
                @Override
                public void onFail(Exception e) {
                    Toast.makeText(getActivity(), "获取用户失败,请检查网络设置!", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onSuccess(List<Yhjbqk> list) {
                    showUserChoiceDialog(list);
                }
            });
        }

        private void showUserChoiceDialog(List<Yhjbqk> users) {
            final List<Yhjbqk> userList = users;

            int checkedPosition = 0;
            Yhjbqk defaultUser = Settings.DEFAULT_YHJBQK;
            if (userList.size() > 0 && defaultUser != null) {
                for (int i = 0; i < userList.size(); i++) {
                    if (defaultUser.getYhbh().equals(userList.get(i).getYhbh())) {
                        checkedPosition = i;
                        break;
                    }
                }
            }

            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
                    .setTitle("选择默认用户")
                    .setSingleChoiceItems(new ArrayAdapter<Yhjbqk>(getActivity(),
                            android.R.layout.simple_list_item_single_choice, userList), checkedPosition, null)
                    .setNegativeButton("取消", null)
                    .setPositiveButton("确定", (dialog, which) -> {
                        int selectedPosition = ((AlertDialog) dialog).getListView().getCheckedItemPosition();

                        if (selectedPosition != -1) {
                            Yhjbqk user = userList.get(selectedPosition);
                            Settings.setDefaultUser(user);
                        }
                    });
            builder.show();
        }
    }

    public static class WebFragment extends Fragment {

        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            WebView webView = new WebView(getContext());
            webView.loadUrl("file:///android_asset/image_setting_info.html");
            return webView;
        }
    }
}
